package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import com.chad.library.adapter.base.BaseQuickAdapter
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelListAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.ChannelMultipleItemEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_classify_detail.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class ClassifyDetailActivity : AppCompatActivity(), BaseQuickAdapter.RequestLoadMoreListener {
    private var classifyId = 0

    private lateinit var data: ArrayList<ChannelMultipleItemEntity>
    private lateinit var channelListAdapter: ChannelListAdapter
    private var onePageCount = 10
    private var currentPage = 1
    private var isLoadingMore = false

    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_classify_detail)
        RxBus.getDefault().register(this)
        data = ArrayList()
        classifyId = intent.getIntExtra("CLASSIFY_ID", 0)
        tv_title.text = intent.getStringExtra("CLASSIFY_NAME")
        rl_back.setOnClickListener { finish() }
        rv_list.layoutManager = LinearLayoutManager(this)
        channelListAdapter = ChannelListAdapter(data)
        rv_list.adapter = channelListAdapter
        channelListAdapter.setOnLoadMoreListener(this,rv_list)
        rv_list.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL, 4, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))
        setOnRecyclerViewScrollDirectListener(rv_list)

        requestKnowledge()
        bindMusicService()
        channelListAdapter.setOnItemClickListener { adapter, view, position ->
            when (data[position].knowledgeType) {
                1 -> {
                    val intent = Intent()
                    intent.setClass(this, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("video_id", data[position].id)
                    intent.putExtra("video_author", data[position].authorName)
                    startActivity(intent)
                }
                2 -> {
                    val audioEntity = AudioEntity(data[position].id, NetConstant.REQUEST_SOURCE + data[position].fileAddress, data[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + data[position].coverImg)
                    mPlayerManager!!.playMusic(audioEntity)
                }
                3 -> {
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("document_title", data[position].knowledgeTitle)
                    intent.putExtra("document_id", data[position].id)
                    startActivity(intent)
                }
                else -> {

                }
            }
        }

        //setOnRecyclerViewScrollDirectListener(rvList)
    }


    override fun onLoadMoreRequested() {
        isLoadingMore = true
        currentPage += 1
        requestKnowledge()
    }


    private fun requestKnowledge() {
        val map = HashMap<String, Any>()
        map["classifyId"] = classifyId
        map["currentPage"] = currentPage
        map["onePageCount"] = onePageCount
        val jsonObject = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_KNOWLEDGE_LIST)
                .tag(this)
                .upJson(jsonObject)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {

                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getInt("code")
                        if (code == 200) {


                            if (isLoadingMore) {
                                val loadingMoreData = ArrayList<ChannelMultipleItemEntity>()
                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")

                                    loadingMoreData.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle
                                            , knowledgeDescribe, knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }

                                if (loadingMoreData.isEmpty()) {
                                    channelListAdapter.loadMoreEnd()
                                    return
                                }
                                channelListAdapter.addData(loadingMoreData)
                                channelListAdapter.loadMoreComplete()

                            } else {
                                this@ClassifyDetailActivity.data.clear()
                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")

                                    this@ClassifyDetailActivity.data.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle
                                            , knowledgeDescribe, knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }
                            }
                            if (this@ClassifyDetailActivity.data.isEmpty()) {
                                channelListAdapter.emptyView = LayoutInflater.from(this@ClassifyDetailActivity).inflate(R.layout.view_empty, null)
                            }
                            channelListAdapter.notifyDataSetChanged()

                        }
                    }
                })
    }


    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@ClassifyDetailActivity, mPlayerManager!!, rl_container)
        }
    }

    private fun bindMusicService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }


    private fun setOnRecyclerViewScrollDirectListener(rvList: RecyclerView) {
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    //todo 隐藏播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(false)
                        }
                    }

                } else {
                    //todo 显示播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(true)
                        }
                    }
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.getDefault().unregister(this)

        mPlayerBarView = null

        unbindService(conn)
    }
}
